package dian.qing.li.demo.security.utils;

import lombok.experimental.UtilityClass;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密工具类
 *
 * @Modify:
 * @Date: 2019/11/26
 */
@UtilityClass
public class MD5Utils {
    private static final Logger LOG = LoggerFactory.getLogger(MD5Utils.class);
    public static final String EMPTY_STRING = "";
    public static final int DEFAULT_COUNT = 3;

    /**
     * md5加密:UTF-8
     *
     * @param source 明文
     * @Author: liqingdian
     */
    public static String md5(String source) {
        return md5(source, StandardCharsets.UTF_8, true);
    }

    /**
     * 生成密码
     *
     * @param password 密码明文
     * @param count    加密次数
     * @Author: liqingdian
     */
    public static String password(String password, int count) {
        String pwd = md5(password);
        for (int i = 0; i < count; i++) {
            pwd = md5(pwd);
        }
        return pwd;
    }

    /**
     * md5加密
     *
     * @param source  明文
     * @param charset 字符集
     * @param upper   是否大写
     * @Author: liqingdian
     */
    public static String md5(String source, Charset charset, boolean upper) {
        if (StringUtils.isBlank(source)) {
            return EMPTY_STRING;
        }
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(source.getBytes(charset));
            byte[] b = md.digest();
            StringBuffer buf = new StringBuffer();
            for (int offset = 0; offset < b.length; ++offset) {
                int i = b[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            if (upper) {
                return buf.toString().toUpperCase();
            }
            return buf.toString().toLowerCase();
        } catch (NoSuchAlgorithmException e) {
            LOG.error(e.getMessage(), e);
        }
        return EMPTY_STRING;
    }
}
